import { createRouter, createWebHistory } from "vue-router";
import { routes } from "./routers.ts";
import { useUserStore } from "@/store";

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

/**
 * 全局前置守卫
 */
export const routerBeforeEach = () => {
  router.beforeEach(async (to, from) => {
    const token = useUserStore().token;
    // console.log(token == null);
    // console.log(to.name);
    if (
      // 检查用户是否已登录
      !token &&
      // ❗️ 避免无限重定向
      to.name !== "testLogin"
    ) {
      // 将用户重定向到登录页面
      return { name: "testLogin" };
    }
  });
};

export default router;
